import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { SetupStoreId } from '@/enum';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared';

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const authStore = useAuthStore();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive({
    userId: '',
    userName: '',
    roles: [] as string[],
    buttons: [] as string[]
  });

  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;

    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles?.includes(VITE_STATIC_SUPER_ROLE);
  });

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    recordUserId();

    clearAuthStorage();

    authStore.$reset();

    if (!route.meta.constant) {
      await toLogin();
    }

    tabStore.cacheTabs();
    routeStore.resetStore();
  }

  /** Record the user ID of the previous login session Used to compare with the current user ID on next login */
  function recordUserId() {
    if (!userInfo.userId) {
      return;
    }

    // Store current user ID locally for next login comparison
    localStg.set('lastLoginUserId', userInfo.userId);
  }

  /**
   * Check if current login user is different from previous login user If different, clear all tabs
   *
   * @returns {boolean} Whether to clear all tabs
   */
  function checkTabClear(): boolean {
    if (!userInfo.userId) {
      return false;
    }

    const lastLoginUserId = localStg.get('lastLoginUserId');

    // Clear all tabs if current user is different from previous user
    if (!lastLoginUserId || lastLoginUserId !== userInfo.userId) {
      localStg.remove('globalTabs');
      tabStore.clearTabs();

      localStg.remove('lastLoginUserId');
      return true;
    }

    localStg.remove('lastLoginUserId');
    return false;
  }

  /**
   * Login
   *
   * @param userName User name
   * @param password Password
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(userName: string, password: string, redirect = true) {
    startLoading();

    const { data: loginUserInfo, error } = await fetchLogin(userName, password);

    // 添加调试信息
    console.log('=== 登录响应调试信息 ===');
    console.log('loginUserInfo:', loginUserInfo);
    console.log('loginUserInfo类型:', typeof loginUserInfo);
    console.log('loginUserInfo.id:', loginUserInfo?.id);
    console.log('loginUserInfo.username:', loginUserInfo?.username);
    console.log('loginUserInfo.flag:', loginUserInfo?.flag);
    console.log('error:', error);
    console.log('error类型:', typeof error);

    if (!error) {
      // 适配后端返回的用户信息格式
      if (loginUserInfo) {
        console.log('=== 登录成功后的用户信息处理 ===');
        console.log('处理前的userInfo:', { ...userInfo });

        // 处理字段名映射 - 根据你的User模型
        userInfo.userId = loginUserInfo.userId || loginUserInfo.id?.toString() || '';
        userInfo.userName = loginUserInfo.userName || loginUserInfo.username || '';

        // 根据flag字段设置角色
        const roles = [];
        if (loginUserInfo.flag === 1) {
          roles.push('admin'); // 管理员
        } else if (loginUserInfo.flag === 2) {
          roles.push('user'); // 有效用户
        } else {
          roles.push('guest'); // 其他状态
        }
        userInfo.roles = (loginUserInfo.roles as string[]) || roles;
        userInfo.buttons = (loginUserInfo.buttons as string[]) || [];

        // 保存其他字段
        Object.assign(userInfo, loginUserInfo);

        console.log('处理后的userInfo:', { ...userInfo });
        console.log('userInfo.userId:', userInfo.userId);
        console.log('userInfo.userName:', userInfo.userName);
        console.log('userInfo.roles:', userInfo.roles);
      }

      // 设置一个简单的token用于标识登录状态
      const simpleToken = `user_${userInfo.userId}_${Date.now()}`;
      localStg.set('token', simpleToken);
      token.value = simpleToken;

      // Check if the tab needs to be cleared
      const isClear = checkTabClear();
      let needRedirect = redirect;

      if (isClear) {
        // If the tab needs to be cleared,it means we don't need to redirect.
        needRedirect = false;
      }
      await redirectFromLogin(needRedirect);

      window.$notification?.success({
        title: $t('page.login.common.loginSuccess'),
        content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
        duration: 4500
      });
    } else {
      console.log('登录失败，调用resetStore');
      resetStore();
    }

    endLoading();
  }

  async function getUserInfo() {
    // 如果已经有用户ID，直接使用；否则返回false
    if (!userInfo.userId) {
      console.log('getUserInfo: 没有用户ID，跳过请求');
      return false;
    }

    console.log('=== getUserInfo 调试信息 ===');
    console.log('当前userInfo.userName:', userInfo.userName);
    console.log('当前userInfo.userId:', userInfo.userId);

    const { data: info, error } = await fetchGetUserInfo(userInfo.userId);

    if (!error && info) {
      console.log('=== getUserInfo 响应调试信息 ===');
      console.log('info:', info);
      console.log('info.id:', info.id);
      console.log('info.username:', info.username);
      console.log('info.flag:', info.flag);

      // 处理字段名映射 - 根据你的User模型
      userInfo.userId = info.userId || info.id?.toString() || userInfo.userId;
      userInfo.userName = info.userName || info.username || userInfo.userName;

      // 根据flag字段设置角色
      const roles = [];
      if (info.flag === 1) {
        roles.push('admin'); // 管理员
      } else if (info.flag === 2) {
        roles.push('user'); // 有效用户
      } else {
        roles.push('guest'); // 其他状态
      }
      userInfo.roles = (info.roles as string[]) || roles;
      userInfo.buttons = (info.buttons as string[]) || [];

      // 保存其他字段
      Object.assign(userInfo, info);
      return true;
    }

    return false;
  }

  async function initUserInfo() {
    const hasToken = getToken();

    if (hasToken) {
      const pass = await getUserInfo();

      if (!pass) {
        resetStore();
      }
    }
  }

  return {
    token,
    userInfo,
    isStaticSuper,
    isLogin,
    loginLoading,
    resetStore,
    login,
    initUserInfo
  };
});
